package com.fengye.cluster.engine;

import com.fengye.cluster.ClusterStrategy;
import com.fengye.cluster.ClusterStrategyEnum;
import com.fengye.cluster.impl.*;
import com.google.common.collect.Maps;

import java.util.Map;

/**
 * @Author fengye
 * @Date 2023/2/15 13:32
 **/
public class ClusterEngine {

    private final static Map<ClusterStrategyEnum, ClusterStrategy> clusterStrategyMap = Maps.newConcurrentMap();

    static {
        clusterStrategyMap.put(ClusterStrategyEnum.RANDOM, new RandomClusterStragyImpl());
        clusterStrategyMap.put(ClusterStrategyEnum.HASH, new HashClusterStrategyImpl());
        clusterStrategyMap.put(ClusterStrategyEnum.POLLING, new PollingClusterStrategyImpl());
        clusterStrategyMap.put(ClusterStrategyEnum.WEIGHT_POLLING, new WeightPollingClusterStrategyImpl());
        clusterStrategyMap.put(ClusterStrategyEnum.WEIGHT_RANDOM, new WeightRandomClusterStrategyImpl());
    }

    /**
     * 获取负载均衡算法
     *
     * @param clusterStrategy
     * @return
     */
    public static ClusterStrategy queryClusterStrategy(String clusterStrategy) {
        ClusterStrategyEnum clusterStrategyEnum = ClusterStrategyEnum.queryByCode(clusterStrategy);
        if (clusterStrategyEnum == null) {
            return clusterStrategyMap.get(ClusterStrategyEnum.RANDOM);
        }
        return clusterStrategyMap.get(clusterStrategyEnum);
    }

}
